package com.pos.net.request;

import com.pos.R;
import com.pos.net.base.AuthFailureError;
import com.pos.net.base.NetworkResponse;
import com.pos.net.base.Response;
import com.pos.net.base.Response.ErrorListener;
import com.pos.net.base.Response.Listener;
import com.pos.net.base.VolleyError;
import com.pos.net.netparam.RequestUrls;
import com.pos.net.request.interfa.BaseRequestListener;
import com.pos.net.request.interfa.JsonRequestListener;
import com.pos.net.request.interfa.StringRequestListener;
import com.pos.net.toolbox.HttpHeaderParser;
import com.pos.net.toolbox.StringRequest;
import com.pos.set.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * @description:数据请求(抽象)
 * @author cai
 * @time:2014年12月11日下午12:22:31
 */
public abstract class DataRequest extends BaseRequest<String> {
	/**
	 * json类型字符传导模式网络,开始请求
	 * 
	 * @param url
	 *            请求地址
	 * @param requestMethod
	 *            网络请求方式，Method.GET==0, "get"方式; Method.POST==1, "post"方式
	 * @param requstData
	 *            请求数据
	 * @param requestId
	 *            请求id
	 * @param listener
	 *            监听接口
	 */
	public void startRequest(String url, int requestMethod, String requstData, final int requestId,
                             final BaseRequestListener listener) {
		super.startBaseRequest(url, requestMethod, requstData, requestId, listener);
	}

	@Override
	public void doRequest(final String url, int requestMethod, final String requstData, final int requestId,
                          final BaseRequestListener listener) {
		request = new StringRequest(requestMethod, url, new Listener<String>() {

			@Override
			public void onResponse(String response) {
				Log.e("response", response);
				if (listener instanceof JsonRequestListener) {
					JSONObject jsonObject;
					try {
						jsonObject = new JSONObject(response);

						if (url.contains(RequestUrls.checkNewVersion)) {
							((JsonRequestListener) listener).onSuccess(requestId, url, jsonObject);
						} else {

							JSONObject headResp = jsonObject.optJSONObject("headResp");

							int retCode = headResp.optInt("retCode", 0);
							if (retCode == 0) {
								((JsonRequestListener) listener).onSuccess(requestId, url, jsonObject);
							} else if (retCode == 1) {
								listener.onError(requestId, 1, "用户登录已过期，请重新登录");
							} else if (retCode == 2) {
								listener.onError(requestId, 2, "app已下架");
							} else if (retCode == 3) {
								listener.onError(requestId, 3,
										headResp.optString("retMsg1") + "," + headResp.optString("retMsg2"));
							} else if (retCode == 4) {
								listener.onError(requestId, 3, headResp.optString("retMsg1"));
							} else {
								((JsonRequestListener) listener).onSuccess(requestId, url, jsonObject);
							}
						}
					} catch (JSONException e) {
						listener.onError(requestId, 0, mContext.getString(R.string.net_request_error));
					}

				} else if (listener instanceof StringRequestListener) {
					((StringRequestListener) listener).onSuccess(requestId, url, response);
				}

			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				listener.onError(requestId, 0, mContext.getString(R.string.net_request_fail));

			}
		}) {

			@Override
			public byte[] getBody() throws AuthFailureError {
				if (requstData == null) {
					return super.getBody();
				} else {
					return requstData.getBytes();
				}
			}

			/*
			 * (non-Javadoc)
			 * 
			 * @see com.android.volley.Request#getHeaders()
			 */
			@Override
			public Map<String, String> getHeaders() throws AuthFailureError {

				return getPrivateHeaders();
			}

			/*
			 * (non-Javadoc)
			 * 
			 * @see
			 * com.android.volley.toolbox.StringRequest#parseNetworkResponse
			 * (com.android.volley.NetworkResponse)
			 */
			@Override
			protected Response<String> parseNetworkResponse(NetworkResponse response) {
				String parsed;
				try {
					parsed = new String(response.data, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					parsed = new String(response.data);
				}
				return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
			}

		};

	}

	/**
	 * 获取私有请求头
	 */
	public abstract Map<String, String> getPrivateHeaders();

	/*
	 * 方法的作用: 解析volley返回cookie
	 */
	public String parseVooleyCookie(String cookie) {
		StringBuilder sb = new StringBuilder();
		String[] cookievalues = cookie.split(";");
		for (int j = 0; j < cookievalues.length; j++) {
			String[] keyPair = cookievalues[j].split("/");
			for (int i = 0; i < keyPair.length; i++) {
				if (keyPair.length == 2) {
					if (keyPair[1].contains("cookieSysUserId") || keyPair[1].contains("JSESSIONID")) {
						sb.append(keyPair[1]);
						sb.append(";");
						break;
					}
				} else {
					if (keyPair[0].contains("cookieEmployeeId")) {
						sb.append(keyPair[0]);
						sb.append(";");
						break;
					}
				}
			}
		}
		return sb.toString();
	}
}
